/**
 * API调试工具
 */

import { http } from "@/utils/http";

/**
 * 测试API连接状态
 */
export const testApiConnections = async () => {
  const results = [];

  // 测试认证接口
  try {
    console.log("测试: GET /auth/check");
    const authResult = await http.request("get", "/auth/check");
    results.push({
      path: "/auth/check",
      method: "GET",
      status: "success",
      response: authResult
    });
  } catch (error) {
    results.push({
      path: "/auth/check",
      method: "GET",
      status: "error",
      error: error.message || error
    });
  }

  // 测试用户列表接口
  try {
    console.log("测试: GET /admin/users");
    const usersResult = await http.request("get", "/admin/users", {
      params: { pageNum: 1, pageSize: 10 }
    });
    results.push({
      path: "/admin/users",
      method: "GET",
      status: "success",
      response: usersResult
    });
  } catch (error) {
    results.push({
      path: "/admin/users",
      method: "GET",
      status: "error",
      error: error.message || error
    });
  }

  // 测试角色列表接口
  try {
    console.log("测试: GET /admin/roles");
    const rolesResult = await http.request("get", "/admin/roles");
    results.push({
      path: "/admin/roles",
      method: "GET",
      status: "success",
      response: rolesResult
    });
  } catch (error) {
    results.push({
      path: "/admin/roles",
      method: "GET",
      status: "error",
      error: error.message || error
    });
  }

  return results;
};

/**
 * 测试特定API路径
 */
export const testSpecificApi = async (
  method: string,
  path: string,
  options?: any
) => {
  try {
    console.log(`测试: ${method.toUpperCase()} ${path}`);
    const result = await http.request(
      method.toLowerCase() as any,
      path,
      options
    );
    return {
      path,
      method: method.toUpperCase(),
      status: "success",
      response: result
    };
  } catch (error) {
    return {
      path,
      method: method.toUpperCase(),
      status: "error",
      error: error.message || error,
      details: error.response || error
    };
  }
};

/**
 * 检查HTTP方法支持情况
 */
export const checkHttpMethods = async (basePath: string) => {
  const methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
  const results = [];

  for (const method of methods) {
    try {
      console.log(`检查: ${method} ${basePath}`);

      let options = {};
      if (method === "POST" || method === "PUT") {
        options = { data: {} };
      }

      const result = await http.request(
        method.toLowerCase() as any,
        basePath,
        options
      );
      results.push({
        method,
        status: "supported",
        response: result
      });
    } catch (error) {
      const errorMessage = error.message || "";
      const isMethodNotSupported =
        errorMessage.includes("not supported") ||
        errorMessage.includes("Method Not Allowed") ||
        error.response?.status === 405;

      results.push({
        method,
        status: isMethodNotSupported ? "not_supported" : "error",
        error: errorMessage,
        statusCode: error.response?.status
      });
    }
  }

  return results;
};

/**
 * 获取详细的错误信息
 */
export const getDetailedError = (error: any) => {
  return {
    message: error.message || "未知错误",
    status: error.response?.status || "N/A",
    statusText: error.response?.statusText || "N/A",
    url: error.config?.url || "N/A",
    method: error.config?.method?.toUpperCase() || "N/A",
    headers: error.config?.headers || {},
    data: error.response?.data || null,
    stack: error.stack || null
  };
};

/**
 * 打印API调试信息
 */
export const printApiDebugInfo = (results: any[]) => {
  console.group("🔍 API调试结果");

  results.forEach((result, index) => {
    const icon = result.status === "success" ? "✅" : "❌";
    console.log(`${icon} ${result.method} ${result.path}`);

    if (result.status === "success") {
      console.log("  响应:", result.response);
    } else {
      console.error("  错误:", result.error);
      if (result.details) {
        console.error("  详情:", result.details);
      }
    }

    if (index < results.length - 1) {
      console.log("---");
    }
  });

  console.groupEnd();
};

/**
 * 一键诊断API问题
 */
export const diagnoseApiIssues = async () => {
  console.log("🚀 开始API诊断...");

  // 1. 测试基础连接
  console.log("1. 测试基础API连接...");
  const connectionResults = await testApiConnections();
  printApiDebugInfo(connectionResults);

  // 2. 检查用户管理接口的HTTP方法支持
  console.log("2. 检查用户管理接口HTTP方法支持...");
  const methodResults = await checkHttpMethods("/admin/users");
  console.table(methodResults);

  // 3. 检查角色管理接口的HTTP方法支持
  console.log("3. 检查角色管理接口HTTP方法支持...");
  const roleMethodResults = await checkHttpMethods("/admin/roles");
  console.table(roleMethodResults);

  // 4. 总结
  const hasErrors = connectionResults.some(r => r.status === "error");
  if (hasErrors) {
    console.error("❌ 发现API连接问题，请检查后端服务状态和路径配置");
  } else {
    console.log("✅ 所有API连接正常");
  }

  return {
    connections: connectionResults,
    userMethods: methodResults,
    roleMethods: roleMethodResults,
    hasErrors
  };
};
